import logging  #使用日志模块
import datetime
import time
import re
import sys
import signal
import os


from SMSClass import MYSMS
from SMTPClass import MYSMTP
from WeatherClass import Weather

TMP='/home/pi/remind/tmp'
FLAG='/home/pi/remind/ZYX_REMIND_FLAG'
USER_CONF='/home/pi/remind/usr.conf'
# 信号处理程序
def sigusr1Handler(signum, frame):  #更新任务计划程序的字典
	print('sigusr1 received!')
	global Schedule
	Schedule={}
	usrfile=open(USER_CONF,'r')
	usrfile_content=usrfile.readlines()
	for k in usrfile_content:
		tmp=k.split('##')
		tmp[0]=tmp[0].strip()
		tmp[1]=tmp[1].strip()
		if tmp[1] not in Schedule.keys():
			Schedule.setdefault(tmp[1],[tmp[0]])
		else:
			Schedule[tmp[1]].append(tmp[0])
	print(Schedule)
	
def sigintHandler(signum, frame):
	print('sigint received!')
	os.remove(TMP)
	os.remove(FLAG)  
	sys.exit(0)
	
	
	
signal.signal(signal.SIGUSR1, sigusr1Handler) #注册信号和处理函数
signal.signal(signal.SIGINT, sigintHandler) 

pidfile=open(TMP,'w')
pidfile.write(str(os.getpid()))  #向临时文件写入pid
pidfile.close()  


env_dist = os.environ #获取环境变量
#print('python env =',env_dist['via'])

sms=MYSMS()
smtpobj=MYSMTP()

#解析usr.conf文件，并更新定时任务列表
Schedule={}
usrfile=open(USER_CONF,'r')
usrfile_content=usrfile.readlines()
for k in usrfile_content:
	tmp=k.split('##')
	tmp[0]=tmp[0].strip()
	tmp[1]=tmp[1].strip()
	if tmp[1] not in Schedule.keys():
		Schedule.setdefault(tmp[1],[tmp[0]])
	else:
		Schedule[tmp[1]].append(tmp[0])
print(Schedule)
		
while True:
	now=datetime.datetime.now()
	for k,v in Schedule.items():
			if 'XX-' in k: #每月提醒
					timeregex=re.compile(r'\d \d\d:\d\d') #用正则表达式匹配日期模式
					mo=timeregex.search(k)
					dt=datetime.datetime.strptime(mo.group(),'%d %H:%M')
					if now.day==dt.day and now.hour==dt.hour and now.minute==dt.minute:
						if 'weather' in v:
							#爬取天气
							try:
								wea=Weather()
								txt=wea.GetWebWeather()
								#print(txt)
								v.remove('weather')
								#发送短信
								if env_dist['via']=="msg":
									sms.SendToMe(txt+'\n'.join(v))
								elif env_dist['via']=="mail":
									smtpobj.SendToMe(txt+'\n'.join(v)) #发送邮件
								else:
									sms.SendToMe(txt+'\n'.join(v))
									smtpobj.SendToMe(txt+'\n'.join(v)) #双重保障
							except:
								print('exception in grabbing weather')  #处理异常
								
						else:
							#把列表中剩余部分转为字符串
							try:
								txt='\n'.join(v)
								print(txt)
								if env_dist['via']=="msg":
									sms.SendToMe('\n'.join(v))
								elif env_dist['via']=="mail":
									smtpobj.SendToMe('\n'.join(v))
								else:
									sms.SendToMe('\n'.join(v))
									smtpobj.SendToMe('\n'.join(v))
							except:
								print('exception in sms.SendToMe')
								os.remove(TMP)
								os.remove(FLAG)
			else:
					timeregex=re.compile(r'\d\d:\d\d')
					mo=timeregex.search(k)					
					dt=datetime.datetime.strptime(mo.group(),'%H:%M')
					if now.hour==dt.hour and now.minute==dt.minute:
						if 'weather' in v:
							#爬取天气
						try:
							w=Weather()
							txt=w.GetWebWeather()
							#print(txt.encode('utf-8'))
							v.remove('weather')
							#发送短信
							if env_dist['via']=="msg":
								sms.SendToMe(txt+'\n'.join(v))
							elif env_dist['via']=="mail":
								smtpobj.SendToMe(txt+'\n'.join(v))
							else:
								sms.SendToMe(txt+'\n'.join(v))
								smtpobj.SendToMe(txt+'\n'.join(v))
						except:
							#logging.debug(f'pasrse failed:{e_msg}')
						#os.remove(TMP)
						#		os.remove(FLAG)
						else:
							#把列表中剩余部分转为字符串
							try:
								txt='\n'.join(v)
								#print(txt)
								if env_dist['via']=="msg":
									sms.SendToMe(txt)
								elif env_dist['via']=="mail":
									smtpobj.SendToMe(txt)
								else:
									sms.SendToMe(txt)
									smtpobj.SendToMe(txt)
							except:
								print('exception in sms.SendToMe')
								
						
	time.sleep(60)

